package edu.scut.course_management.handler;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import edu.scut.course_management.po.Student;
import edu.scut.course_management.po.Teacher;
import edu.scut.course_management.result.JsonResult;
import edu.scut.course_management.result.JsonResultFactory;
import edu.scut.course_management.util.ResponseWritingUtil;

/**
 * 登录成功处理器
 * 登录成功的处理逻辑，返回前端 json 信息提示 “登录成功”
 * 并携带当前登录用户的个人信息
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
     
        Object principle = authentication.getPrincipal();
        Map<String, Object> info = null;
        if (principle instanceof Student) {
            info = ((Student)principle).generateBasicInfoMap();
        }
        else {
            info = ((Teacher)principle).generateBasicInfoMap();
        }
        JsonResult result = JsonResultFactory.getInstance().buildSuccessResult(info);
        ResponseWritingUtil.writeJsonResultToResponse(response, result);
    }
}
